<template>
  <view class="notify-page relative bg-#f5f5f5" style="min-height: 101vh;">
    <u-sticky>
      <view class="bg-#fff">
        <u-tabs :current="activeCircleTab" :list="tabsList" @click="handleChangTab" lineBgSize="cover"></u-tabs>
      </view>
    </u-sticky>
    <view v-for="(item, index) in notifyList" :key="index" class="notify-page-card-box mx-24rpx"
      >
      <view class="notify-card flex">
        <view class="flex w-full  items-center">
          <up-image v-if="item?.fileUrl?.length" width="84rpx" height="84rpx" :src="item?.fileUrl?.[0]" radius="10px"></up-image>
          <view class="card-text ml-34rpx flex-1" @tap="handleClick(item)">
            <view class="flex justify-between items-center mb-10rpx">
              <view class="flex items-center">
                <view  :style="{color:item.readFlag?'#7E7E7E':[101,113,401].includes(item.businessDetailType)?'red':'#000','text-decoration':!item.readFlag&&[101,113,401].includes(item.businessDetailType)?'underline':'none'}" class="font-700 text-28rpx ellipse max-w-360rpx">{{ item.businessDetailTypeDesc }}</view>
                <!-- <view v-if="[101,113,401].includes(item.businessDetailType) && !item.readFlag" class="flex bg-#FF4444 p-8rpx color-#fff text-24rpx ml-16rpx" style="border-radius: 8rpx;">
                   {{ item.businessDetailType === 101 ? '立即确认' : item.businessDetailType === 113 ? '立即发货' : '立即回复' }}
                  <up-icon name="arrow-right" size="18" color="#fff"></up-icon>
                </view> -->
              </view>
              <view class="font-700 text-24rpx"
                style="color:#7E7E7E">{{ formatEventTime(item.messageCreatedTime) }}</view>
            </view>
            <view class="flex justify-between items-center">
              <view v-if="![401].includes(item.businessDetailType)">
                <view class="card-content py-10rpx font-400 text-24rpx overflow-ellipsis" style="color: #7e7e7e;">
                  {{ item.message }}
                </view>
              </view>
              <view v-else>
                <view v-for="(citem, cindex) in item.messageDetail" :key="cindex" class="card-content py-5rpx font-400 text-24rpx overflow-ellipsis" style="color: #7e7e7e;">
                  {{ citem }}
                </view>
              </view>
              <view class="h-full flex items-center">
                <up-icon name="arrow-right" size="18"></up-icon>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- <ProductCard :record="item"></ProductCard> -->
    </view>
    <view v-if="!notifyList.length" class="mt-168rpx w-320rpx m-auto  text-#999999">
      <img class="w-280rpx h-280rpx" :src="emptyImg">
      <view class="text-center">
        暂无消息
      </view>
    </view>
  </view>
  <!-- <CustomTabbar page="notifyList"></CustomTabbar> -->
   <message-modal ref="msgRef" :delay="5" :auto="false" />
</template>

<script setup lang="ts">
import { productManageSupQueryProductSup } from "@/genapi/productManageSup"
import { supplierQuerySupplierInfo } from "@/genapi/supplier"
import { debounce } from '@antfu/utils'
import emptyImg from "@/static/empty.png";
import { onLoad } from '@dcloudio/uni-app'
import { messageLogRead, queryDeliveryAskList } from "@/genapi/_delivery";
import { useSupplierStore } from "@/store";

const supplierStore = useSupplierStore()
const msgRef = ref(null)
onLoad(() => {
  try{
    uni.hideTabBar()
  }catch(err){}

})
const msgTypeMap = ref({
  101: '订单确认',
  113: '订单发货',
  202: '订单变更',
  111: '订单取消',
  114: '订单预付款',
  106: '订单完成',
  109: '采购数减少导致状态变更为已完成',
  112: '异常已解决',
  203: '退货退款',
  204: '退货重发',
  401: '货期咨询',
})
const tabsList = ref([{
  value: '',
  name: '全部'
}, {
  value: '401',
  name: '货期咨询消息'
}])
const activeCircleTab = ref(0)
const notifyList = ref([])
const hasNext = ref<boolean>(true)
let apiParams: any = {
  businessDetailType: '',
  endTime: '',
  day: 30
}
function handleChangTab(key){
  console.log(key)
  activeCircleTab.value = key.index
  apiParams.businessDetailType = key.value
  apiParams.endTime = '',
  notifyList.value = []
  getNotifyList()
}
function gotoNotify(row) {
    uni.navigateTo({
      url: `/pages/deliveryConsultation/index?id=3`
    })
}
function handleClick(row) {
  if(row.messageBusinessType ===1){
    msgRef.value.showMsg(row,0)
   }else{
    if(row.businessDetailType === 401){
      uni.navigateTo({
        url: `/pages/deliveryConsultation/index?id=${row.poId}`
      })
    }else{
      if(row.poId){
        uni.navigateTo({
          url: `/pages/orderDetail/index?id=${row.poId}`,
        })
      }else{
        // uni.switchTab({
        //   url: 'pages/orderList/index'
        // })
        if(row.messageDetail.length === 1){
          uni.navigateTo({
            url: `/pages/orderDetail/index?id=${row.messageDetail[0].poId}`,
          })
        }else{
          supplierStore.setWaitSend(true)
          uni.switchTab({
            url: `/pages/orderList/index`,
          })
        }
      }
    }
   }
}
async function gotoLogin() {
  const isNoLogin = await uni.getStorageSync('isNoLogin')
  if (isNoLogin) {
    uni.navigateTo({
      url: '/pages/login/index'
    })
    return false
  } else {
    return true
  }
}
function search(val: string) {
  notifyList.value.length = 0
  getNotifyList()
}
const searchProduct = debounce(500, search)

async function getNotifyList() {
  const isLogin = await gotoLogin()
  console.log(apiParams)
  if (isLogin) {
    const { data } = await queryDeliveryAskList(apiParams)
    // const { data } = await productManageSupQueryProductSup(apiParams)
    if (data?.code !== 200) return
    else {
      const result = data.data
      if (!result.records)
        return
      notifyList.value = notifyList.value.concat(result.records)
      apiParams.endTime = result.startTime
      // if (result.records)
      let noread = notifyList.value.filter((item: any) => item.readFlag === 0)
      let readed = notifyList.value.filter((item: any) => item.readFlag === 1)
      notifyList.value = []
      notifyList.value = [].concat(noread).concat(readed)
      hasNext.value = result.hasNext
      // notifyList.value = notifyList.value.concat(result.tableData)
      // notifyList.value = notifyList.value.map(item => {
      //   item.productPriceList.sort((a, b) => a.productPrice - b.productPrice)
      //   return item
      // })
      nextTick(()=>{
        // messageLogRead()
      })
    }
  }
}

// 下拉刷新
onPullDownRefresh(async () => {
  notifyList.value.length = 0
  apiParams.endTime = ''
  hasNext.value = true
  await getNotifyList()
  uni.stopPullDownRefresh()
})
// 上拉刷新
onReachBottom(() => {
  // console.log('上拉刷新',hasNext.value)
  if (hasNext.value) {
    //页数累加
    getNotifyList()
  }
})
onShow(async () => {
  notifyList.value.length = 0
  apiParams.endTime = ''
  const isNoLogin = await uni.getStorageSync('isNoLogin')
  messageLogRead().then(
    supplierStore.getMessageCount()
  )
  if (isNoLogin) return
  getNotifyList()
})
onMounted(async () => {
  const { data } = await supplierQuerySupplierInfo({})
  if (data?.code !== 200) return
  else {
    uni.setNavigationBarTitle({
      title: data.data.supplierInfo.supplierName || '产品列表' // 页面标题为"自定义标题"
    });
  }
})
function formatEventTime(eventTime) {
    const now = new Date();
    eventTime = eventTime.replace(/[年月]/g,'/').replace(/[日]/g,'')
    const eventDate = new Date(eventTime);
    const diffInMs = now - eventDate;
    const diffInMinutes = Math.floor(diffInMs / (1000 * 60));
    const diffInHours = Math.floor(diffInMs / (1000 * 60 * 60));

    if (diffInMinutes < 3) {
        return '刚刚';
    } else if (diffInMinutes < 60) {
        return `${diffInMinutes}分钟`;
    } else if (diffInHours < 24) {
        return `${diffInHours}小时`;
    } else {
        return eventTime
    }
}
</script>

<style lang="less" scoped>
.notify-page {
  .notify-card{
    background-color: #fff;
    border-radius: 16rpx;
    box-shadow: 0 0 16px 1px rgba(0, 0, 0, 0.02), 0 0 8px 0px rgba(0, 0, 0, 0.01);
    padding: 24rpx;
    margin: 24rpx 0;
  }
}
</style>
